package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
public class FileUploadController {
    protected String uploadPath = "/static/upload/";
    // 单个文件上传
    @RequestMapping("/fileUpload")
    public String fileUpload(MultipartFile file,
                             HttpServletRequest request) throws IOException {
        String rootPath = request.getServletContext().getRealPath("/");//网站webapp所在真实目录位置
        String uploadPath = "/static/upload/";//指定上传目录
        String fileName =  file.getOriginalFilename();//获取文件名
        String filePath = rootPath + uploadPath;//真实目录拼接指定上传目录


        String message = "上传成功";
        if (!file.isEmpty()) {
            file.transferTo(new File(filePath + fileName));
        }else {
            message = "上传失败";
        }
        request.setAttribute("msg", message);
        request.setAttribute("filePath", filePath+fileName);
        return "upload";
    }
    @RequestMapping("/Uploads")
    public String Uploads(MultipartFile[] files,
                         HttpServletRequest request) throws IOException {
        String rootPath = request.getServletContext().getRealPath("/");//网站webapp所在真实目录位置
        String uploadPath = "/static/upload/";//指定上传目录
        String message = "上传成功";
        for (MultipartFile file : files) {
            String fileName =  file.getOriginalFilename();
            String filePath = rootPath + uploadPath;
            if (!file.isEmpty()) {
                file.transferTo(new File(filePath + fileName));
                message = "上传成功";
            }else {
                message = "上传失败";
            }
        }
        request.setAttribute("msg", message);
        return "upload";
    }
}
